import time

from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.enum.table import WD_CELL_VERTICAL_ALIGNMENT
from docx import Document
from docx.shared import Pt,Inches,Cm, RGBColor
from docx.oxml.ns import qn
from PIL import ImageOps
from PIL import Image
import datetime
from pdf2image import convert_from_path
import fitz
from io import BytesIO
from bid.generate.models import ExFile, ExBid
from zentao.settings import ROOT_FOLDER
# 创建一个新的Word文档

def generate_team(content_table,team_bidSocialInsurances, save_path, bid_id,extra={}):
    doc = Document()

    # 序号
    title_id = '99.'
    # title_id = ''

    # 定义标题和正文的样式
    # title0="（十四）项目团队"
    title0="（九十九）项目团队"
    content0=None
    # title1="14.1.人员配置情况"
    title1= f"{title_id}1.人员配置情况"
    if extra:
        content1=f"我司承诺已完全理解且满足招标文件中的项目组织人员要求、团队规模及项目组成员资质。我司拟组建一支{len(content_table)}人专业服务团队，" \
                 f"其中{extra['cnt']}人具有{extra['团队要求']}（具体人员名单：{extra['person']}），" \
                 "且我司有完善合理的团队稳定保障措施。另外，项目组成员100%人员都具备信息系统的开发或实施经验，熟悉项目范围内的系统情况或同类型系统，" \
                 "并从事信息系统工作经验一年以上，能熟练胜任所负责工作。项目组成员主要信息如下："
    else:
        content1 = f"我司承诺已完全理解且满足招标文件中的项目组织人员要求、团队规模及项目组成员资质。我司拟组建一支{len(content_table)}人专业服务团队，" \
                   f"其中9人具有软件类中级及以上证书（具体人员名单：肖建毅、何宇新、许文武、江雄、陈竞、陈耀冲、黄亮、王宇平、龙江喜），" \
                   "且我司有完善合理的团队稳定保障措施。另外，项目组成员100%人员都具备信息系统的开发或实施经验，熟悉项目范围内的系统情况或同类型系统，" \
                   "并从事信息系统工作经验一年以上，能熟练胜任所负责工作。项目组成员主要信息如下："

    # title2="14.1.1.项目组成员名单和分工"
    title2=f"{title_id}1.1.项目组成员名单和分工"
    content2=None
    # title3="14.1.1.1.项目组成员主要信息"
    title3=f"{title_id}1.1.1.项目组成员主要信息"
    content3="项目组成员主要信息应包括成员简历、学历证书、职称证书，同类业绩须附有合同或验收证书等复印件，具体情况如下："

    # content_table=[{"职责分工":"项目负责人","行政办公项目年限（年）":"20年以上项目管理经验","主要持有证书":["信息系统项目管理师（高级）"],
    #                "姓名":"肖建毅","学历":"硕士","本项目中职务":"项目负责人","主要资格证书名称及编号":["企业信息管理师一级：1601000010100109",
    #                                                                       "信息系统项目管理师：15101440604",
    #                                                                       "系统分析师： 17102440043"
    #                                                                      "高级工程师：广电人资(2017)2号"],
    #                 "主要工作经历":["2000-2014年，开展全省办公自动化系统V1.0、V2.0、V3.0等各版本的业务规划、开发上线等工作。","2016-2019年，负责并完成全部企业级管理系统"],
    #                 "以往参与项目情况":["1、2018年，负责组织建设广东电目","2、2019年，负责组织建设广东电网有限责任公司应用级灾备中心二期建设"],
    #                 "学历截图":["./招投标文件生成(data)/图片1.png","./招投标文件生成(data)/10.jpg"],
    #                 "证书截图":["./招投标文件生成(data)/图片2.png","./招投标文件生成(data)/图片2.png"]},
    #                {"职责分工": "项目负责人", "行政办公项目年限（年）": "20年以上项目管理经验", "主要持有证书": ["信息系统项目管理师（高级）"],
    #                 "姓名": "陈颖", "学历": "硕士", "本项目中职务": "项目负责人", "主要资格证书名称及编号": ["企业信息管理师一级：1601000010100109",
    #                                                                               "信息系统项目管理师：15101440604",
    #                                                                               "系统分析师： 17102440043"
    #                                                                               "高级工程师：广电人资(2017)2号"],
    #                 "主要工作经历": ["2000-2014年，开展全省办公自动化系统V1.0、V2.0、V3.0等各版本的业务规划、开发上线等工作。", "2016-2019年，负责并完成全部企业级管理系统"],
    #                 "以往参与项目情况": ["1、2018年，负责组织建设广东电目", "2、2019年，负责组织建设广东电网有限责任公司应用级灾备中心二期建设"],
    #                 "学历截图": ["./招投标文件生成(data)/图片1.png", "./招投标文件生成(data)/10.jpg"],
    #                 "证书截图": ["./招投标文件生成(data)/图片2.png", "./招投标文件生成(data)/图片2.png"]}]

    styles = [
        (title0, content0, 16, True, WD_PARAGRAPH_ALIGNMENT.CENTER, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY, 1),
        (title1, content1, 15, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY, 2),
        (title2, content2, 15, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY, 3),
        (title3, content3, 12, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY, 4),
    ]

    # new_style = (title1, content1, 16, True, WD_PARAGRAPH_ALIGNMENT.CENTER, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY)
    # styles.append(new_style)

    # 添加标题和正文到文档中
    for style in styles:
        title, content, title_font_size, title_bold, title_alignment, content_font_size, content_bold, content_alignment, level = style

        # 添加标题
        paragraph = doc.add_heading(level=level)
        run = paragraph.add_run(title)
        run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
        run.font.italic = False  # 关闭斜体
        run.font.size = Pt(title_font_size)
        run.bold = title_bold
        paragraph.alignment = title_alignment
        # 设置字体为宋体
        run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
        paragraph.paragraph_format.line_spacing = 1.5
        # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
        paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(5)  # 设置段后间距为5磅

        # if title=="14.1.1.项目组成员名单和分工":
        if title==f"{title_id}1.1.项目组成员名单和分工":
            table = doc.add_table(rows=len(content_table) + 1, cols=5)

            # 设置表格列宽
            col_widths = [1.59, 4.42, 2.56, 3.22, 3.78]
            # 应用每列的宽度
            for col, width in zip(table.columns, col_widths):
                for cell in col.cells:
                    cell.width = Cm(width)

            # 设置表格样式以显示框线
            table.style = 'Table Grid'
            headers = ["序号", "职责分工", "负责人姓名", "行政办公项目年限（年）", "主要持有证书"]
            # 填写表头
            for i, header in enumerate(headers):
                cell = table.cell(0, i)
                cell.text = header
                # 设置单元格的垂直居中对齐
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.bold = True  # 设置表头文本加粗
                        run.font.size = Pt(12)  # 设置字体为小四号
                        run.font.name = '宋体'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                        paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER


            def set_cell_font(cell, text):
                cell.text = text
                # 设置单元格的垂直居中对齐
                cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER
                for paragraph in cell.paragraphs:
                    for run in paragraph.runs:
                        run.font.size = Pt(12)  # 设置字体为小四号
                        run.font.name = '宋体'
                        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
                        paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER


            def table_wr(i):
                # 填写内容
                row = table.rows[i + 1]  # 第二行用于填写内容
                set_cell_font(row.cells[0], str(i + 1))  # 序号
                set_cell_font(row.cells[1], content_table[i]["职责分工"])
                set_cell_font(row.cells[2], content_table[i]["姓名"])
                set_cell_font(row.cells[3], content_table[i]["行政办公项目年限（年）"])
                set_cell_font(row.cells[4], '\n'.join(content_table[i]["主要持有证书"]))
            for i in range(len(content_table)):
                table_wr(i)

            #分页符
            doc.add_page_break()

        # 添加正文
        if content is not None:
            paragraph = doc.add_paragraph()
            run = paragraph.add_run(content)
            run.font.size = Pt(content_font_size)
            run.bold = content_bold
            paragraph.alignment = content_alignment
            # 设置字体为宋体
            run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
            run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
            paragraph.paragraph_format.line_spacing = 1.5  # 设置行间距为1.5倍
            paragraph.paragraph_format.first_line_indent = Pt(24)  # 设置首行缩进为2个字符（大约24磅）

    l = len(content_table)-1

    def image_write(data):

        paragraph = doc.add_paragraph()
        # 在段落中添加图片
        # 假设图片文件名为'image.png'，位于当前目录下
        image_path = data
        run = paragraph.add_run()

        #一直插图片
        judge = False
        while not judge:
            try:
                run.add_picture(image_path, width=Inches(6))  # 设置图片宽度为4英寸
                judge = True
            except:
                print(image_path)

        paragraph.alignment = 1

    # 图片裁剪
    def trim_and_add_border(image):
        # 将图片转换为灰度图像，便于处理
        grayscale_image = image.convert('L')

        width = grayscale_image.width
        height = grayscale_image.height

        # 找到需要裁剪的边界
        def find_borders(img):
            invert_img = ImageOps.invert(img)
            bbox = invert_img.getbbox()
            return bbox

        borders = find_borders(grayscale_image)

        if not borders:
            borders = (0, 0, width, height)
        else:
            left, top, right, bottom = borders
            left = max(0, left - width // 20)
            right = min(width, right + width // 20)
            top = max(0, top - height // 20)
            bottom = min(height, bottom + height // 20)

            if (bottom - top) / (right - left) > 1.414:
                new_width = int((bottom - top) / 1.415)
                left = min(left, max(0, (width - new_width) // 2))
                right = max(right, min(width, new_width + (width - new_width) // 2))

                # print((bottom - top) / (right - left))

            borders = (left, top, right, bottom)

        trimmed_image = image.crop(borders)

        return trimmed_image

    def pdf_image(pdf_path):
        # st = time.time()
        images = convert_from_path(pdf_path)
        # 遍历所有图片并将其添加到Word文档中
        for image in images:
            image = trim_and_add_border(image)
            # image.save('/media/977GB/wcj_work/投标文件生成/团队生成.png')
            # 保存图片到临时文件
            temp_image_path = 'temp_image.png'
            image.save(temp_image_path, 'JPEG')

            # 将图片添加到Word文档
            # doc.add_picture(temp_image_path, width=Inches(6))  # 设置插入的图片大小为6英寸
            # 在文档中添加一个新的段落
            paragraph = doc.add_paragraph()

            # 设置段落的对齐方式为居中
            paragraph.alignment = 1  # 1代表居中对齐

            # 创建一个运行并添加图片
            run = paragraph.add_run()
            run.add_picture(temp_image_path, width=Inches(6))  # 设置插入的图片大小为6英寸

    for row_index in range(len(content_table)):
        # title="14.1.1.1."+str(row_index+1)+content_table[row_index]["姓名"]
        title=f"{title_id}1.1.1."+str(row_index+1)+content_table[row_index]["姓名"]
        content=None
        style=(title, content, 12, True, WD_PARAGRAPH_ALIGNMENT.LEFT, 12, False, WD_PARAGRAPH_ALIGNMENT.JUSTIFY, 5)
        title, content, title_font_size, title_bold, title_alignment, content_font_size, content_bold, content_alignment, level = style

        # 添加标题
        paragraph = doc.add_heading(level=level)
        run = paragraph.add_run(title)
        run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
        run.font.italic = False  # 关闭斜体
        run.font.size = Pt(title_font_size)
        run.bold = title_bold
        paragraph.alignment = title_alignment
        # 设置字体为宋体
        run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
        paragraph.paragraph_format.line_spacing = 1.5
        # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
        paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(5)  # 设置段后间距为5磅

        # 添加一个表格
        # 添加一个表格，2行6列（第一行每个键和值分别占用一个单元格，第二行用于合并单元格）
        if content_table[row_index]["本项目中职务"] == '项目负责人':
            table = doc.add_table(rows=5, cols=4)
        else:
            table = doc.add_table(rows=4, cols=4)

        table.style = 'Table Grid'

        # 定义字体和大小
        font_name = '宋体'
        font_size = Pt(12)

        # 第一行
        row1 = table.rows[0]
        keys = ["姓名", "学历"]
        values = [content_table[row_index]["姓名"], content_table[row_index]["学历"]]

        # 遍历键和值，填充到第一行表格中
        for i, (key, value) in enumerate(zip(keys, values)):
            # 键单元格
            key_cell = row1.cells[2 * i]

            # 设置单元格的垂直居中对齐
            cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

            key_run = key_cell.paragraphs[0].add_run(key)
            key_run.bold = True
            key_run.font.name = font_name
            key_run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
            key_run.font.size = font_size
            key_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

            # 值单元格
            value_cell = row1.cells[2 * i + 1]

            value_run = value_cell.paragraphs[0].add_run(value)
            value_run.font.name = font_name
            value_run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
            value_run.font.size = font_size
            value_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER

        # 第二行
        def row_write(n, key):
            row2 = table.rows[n]  # n=1
            # 在第二行的第一个单元格中填写“本项目中职务：”，并设置加粗
            duty_cell = row2.cells[0]

            duty_run = duty_cell.paragraphs[0].add_run(key)
            duty_run.bold = True
            duty_run.font.name = font_name
            duty_run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
            duty_run.font.size = font_size
            duty_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            # 设置单元格的垂直居中对齐
            duty_cell.vertical_alignment = WD_CELL_VERTICAL_ALIGNMENT.CENTER

            # 合并第二行的剩余单元格
            table.cell(n, 1).merge(table.cell(n, 3))
            # 在合并后的单元格中填写
            project_leader_cell = row2.cells[1]
            if key == '本项目中职务':
                project_leader_run = project_leader_cell.paragraphs[0].add_run(content_table[row_index][key])
                project_leader_cell.paragraphs[0].alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
            else:
                project_leader_run = project_leader_cell.paragraphs[0].add_run("\n".join(content_table[row_index][key]))
            project_leader_run.font.name = font_name
            project_leader_run._element.rPr.rFonts.set(qn('w:eastAsia'), font_name)
            project_leader_run.font.size = font_size

        row_write(1, "本项目中职务")
        row_write(2, "主要资格证书名称及编号")
        row_write(3, "主要工作经历")

        if content_table[row_index]["本项目中职务"] == '项目负责人':
            row_write(4, "以往参与项目情况")

        #表格后面添加一个回车
        paragraph = doc.add_paragraph()

        # 添加学历证书 content4_table["学历截图"]
            # print(time.time() - st)

        # def pdf_image(pdf_path):
        #     st = time.time()
        #     # images = convert_from_path(pdf_path,dpi=100)
        #     # # 遍历所有图片并将其添加到Word文档中
        #     # for image in images:
        #     #     # image.save('/media/977GB/wcj_work/投标文件生成/团队生成.jpg')
        #     #     # 保存图片到临时文件
        #     #     temp_image_path = 'temp_image.jpg'
        #     #     image.save(temp_image_path, 'JPEG')
        #     #
        #     #     # 将图片添加到Word文档
        #     #     doc.add_picture(temp_image_path, width=Inches(6))  # 设置插入的图片大小为6英寸
        #     # 打开PDF文件
        #     pdf_document = fitz.open(pdf_path)
        #     total_pages = pdf_document.page_count
        #
        #     for page_num in range(total_pages):
        #         # 获取单页
        #         page = pdf_document.load_page(page_num)
        #
        #         # 将页面转换为图像
        #         pix = page.get_pixmap(matrix=fitz.Matrix(2, 2))
        #
        #         pix.save('/media/977GB/wcj_work/投标文件生成/团队生成1.png')
        #
        #         # 使用BytesIO创建内存中的字节流
        #         img_stream = BytesIO(pix.tobytes("png"))  # 直接从Pixmap获取PNG格式的字节流
        #
        #         # 将图像添加到Word文档中
        #         # doc.add_paragraph(f"Page {page_num + 1}")
        #         doc.add_picture(img_stream, width=Inches(6))  # 调整图像大小以适应页面
        #     print(time.time()-st)

        for _type in ["学历截图","证书截图"]:
            for filename in content_table[row_index][_type]:
                if filename.endswith('.pdf'):
                    pdf_image(filename)
                else:
                    image_write(filename)

        # 插入分页符，确保下一张图片从新页开始
        doc.add_page_break()
        # image_write(content_table[i]["学历截图"])
        # image_write(content_table[i]["证书截图"])

    #添加社保缴纳证明
    # 添加标题
    paragraph = doc.add_heading(level=2)
    run = paragraph.add_run(f'{title_id}2.社保缴纳证明')
    run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
    run.font.italic = False  # 关闭斜体
    # paragraph = doc.add_paragraph()
    # run = paragraph.add_run('14.2.社保缴纳证明')
    # run = paragraph.add_run()
    run.font.size = Pt(15)
    run.bold = True
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
    # 设置字体为宋体
    run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
    run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
    paragraph.paragraph_format.line_spacing = 1.5
    # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
    paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
    paragraph.paragraph_format.space_after = Pt(5)  # 设置段后间距为5磅

    #添加内容
    l = len(team_bidSocialInsurances)
    for i, obj in enumerate(team_bidSocialInsurances, start=1):
        # 添加子标题
        # paragraph = doc.add_paragraph()
        # # run = paragraph.add_run(f'14.2.{i}.{obj[1]}')
        # run = paragraph.add_run(f'{title_id}2.{i}.{obj[1]}')
        paragraph = doc.add_heading(level=3)
        run = paragraph.add_run(f'{title_id}2.{i}.{obj[1]}')
        run.font.color.rgb = RGBColor(0, 0, 0)  # 设置颜色为黑色
        run.font.italic = False  # 关闭斜体
        run.font.size = Pt(15)
        run.bold = True
        paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.LEFT
        # 设置字体为宋体
        run.font.name = 'SimSun'  # 英文名'SimSun'对应宋体
        run._element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')  # 确保中文字符使用宋体
        paragraph.paragraph_format.line_spacing = 1.5
        # paragraph.paragraph_format.first_line_indent = Cm(1) #悬挂缩进1cm
        paragraph.paragraph_format.space_before = Pt(5)  # 设置段前间距为5磅
        paragraph.paragraph_format.space_after = Pt(5)  # 设置段后间距为5磅

        filename = obj[2]
        if filename.endswith('.pdf'):
            pdf_image(filename)
        else:
            image_write(filename)

        # 插入分页符，确保下一张图片从新页开始
        if i < l:
            doc.add_page_break()

    # 保存文档的路径
    current_time = datetime.datetime.now()
    filename = current_time.strftime(save_path)
    # 保存文档的路径
    filepath_modified = filename
    doc.save(filepath_modified)

    # 将文件添加到文件数据库表中
    teamFile = ExFile.objects.create(
        path=filepath_modified.replace(ROOT_FOLDER, ''),
        type='docx',
        comment='',
        uploadDate=time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    )

    # 更新数据库，团队管理的文件
    ExBid.objects.filter(id=bid_id).update(team=teamFile)


